/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package admin.reportes;

import DBMS.DataBaseManager;
import clases.Matriz;
import clases.Reportable;
import clases.Reporte;
import clases.Totalizacion;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author Gimbet
 */
public class CargarTotalizacion extends org.apache.struts.action.Action {

    /*
     * forward name="success" path=""
     */
    private static final String SUCCESS = "success";
    private static final String FAILURE = "failure";

    /**
     * This is the action called from the Struts framework.
     *
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        DataBaseManager dbms = DataBaseManager.getInstance();
        String idReporte = (String) request.getParameter("idrep");
        if (idReporte == null){
            Reporte r = new Reporte();
            r.setMensaje("Error mostrando totalizaciones");
            request.setAttribute("reporte",r);
            return mapping.findForward(FAILURE);
        }
        Reporte r = new Reporte();
        r.setIdreporte(Integer.valueOf(idReporte));
        ArrayList<Reportable> matrices = dbms.consultarElementosReporte(r);
        if (matrices.isEmpty()){
              request.setAttribute("reporte",r);
              r.setMensaje("Debe primero añadir una matriz para agregar totalizaciones");
              return mapping.findForward(FAILURE);
        }
        ArrayList<Totalizacion> totalizaciones = new ArrayList<Totalizacion>();
        for (Reportable rep : matrices){
            Matriz m = (Matriz) rep;
            ArrayList<Totalizacion> totalizacion= dbms.consultarTotalizaciones(m.getIdMatriz());

            for (Totalizacion t : totalizacion){
                totalizaciones.add(t);
            }
        }
        if (totalizaciones.isEmpty()){
          request.setAttribute("reporte",r);
          r.setMensajeOK("No hay totalizaciones agregadas");
          return mapping.findForward(SUCCESS);
        }
        request.setAttribute("totalizaciones", totalizaciones);
        request.setAttribute("reporte",r);
        return mapping.findForward(SUCCESS);
    }
}
